package net.example.model.common;

import com.oraycn.omcs.utils.BufferUtils;
import com.oraycn.omcs.utils.SerializeUtils;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;

/**
 * Created by ZN on 2017/2/8.
 */

public class LinkText {
    private String text="";
    private String url="";
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void deserialize(ByteBuf buffer) throws Exception {
        int len = buffer.readInt();
        if (len == -1) return;
        this.text = SerializeUtils.readStrIntLen(buffer);
        this.url = SerializeUtils.readStrIntLen(buffer);
    }

    public byte[] serialize() throws Exception {
        ByteBuf body = BufferUtils.newBuffer();
        int totalLen = 0;
        body.writeInt(totalLen);
        byte[] textBytes = this.text.getBytes(StandardCharsets.UTF_8);
        body.writeInt(textBytes.length);
        body.writeBytes(textBytes);
        byte[] urlBytes = this.url.getBytes(StandardCharsets.UTF_8);
        body.writeInt(urlBytes.length);
        body.writeBytes(urlBytes);
        body.resetWriterIndex();
        totalLen += 4 + textBytes.length + 4 + urlBytes.length;
        body.writeInt(totalLen);
        byte[] bytes = new byte[body.writerIndex()];
        body.getBytes(0, bytes);
        return bytes;
    }
}
